package org.example.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.ReferenceCountUtil;
import org.example.netty.handler.MsgStringHandler;
import org.example.utils.LogUtils;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        // 引导类，组装和集成器，负责将不同的netty组件组装在一起
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 定义boss事件轮询组，1表示内部有一个线程
        // 每个线程内部，一个反应器在轮询
        // 一个反应器对应一个Selector
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        // 定义worker事件轮询组
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        serverBootstrap.group(bossGroup, workerGroup);

        // 设置NIO
        serverBootstrap.channel(NioServerSocketChannel.class);

        // 绑定端口
        serverBootstrap.localAddress(8081);

        serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        // 5 装配子通道的流水线
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            /**
             * 有连接到达时会触发此方法
             * @param ch
             * @throws Exception
             */
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                /**
                 * 第一个参数：数据包最大长度
                 * 第二个参数：长度字段起始下标
                 * 第三个参数：长度字段占用的字节数
                 * 第四个参数：长度调整值 = 内容字段偏移量 - 长度字段偏移量 - 长度字段长度
                 * 第五个参数：内容区域起始下标
                 */
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new MsgStringHandler());
            }
        });

        try {
            // 开始绑定服务器，通过调用sync()同步阻塞直到绑定成功
            ChannelFuture future = serverBootstrap.bind().sync();
            LogUtils.info("服务器启动成功，监听端口：" + future.channel().localAddress());

            //
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    static class NettyDiscardHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            try {
                LogUtils.info("收到消息，丢弃如下：");
                while (buf.isReadable()) {
                    System.out.print((char) buf.readByte());
                }
                System.out.println();
            } finally {
                ReferenceCountUtil.release(msg);
            }
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            LogUtils.info("客户端连接断开");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            LogUtils.info(cause.getMessage());
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            LogUtils.info("有新连接进来");
        }
    }

    static class NettyOutHandler extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            LogUtils.info("回写数据");
            super.write(ctx, msg, promise);
        }

        @Override
        public void read(ChannelHandlerContext ctx) throws Exception {
            LogUtils.info("有数据进来");

            ctx.write("welcome to server");
            super.read(ctx);
        }
    }
}
